window.addEventListener("load", async () => {
  // 浏览器是否支持API
  if ("serial" in navigator) {
    (async function () {
      // let portName = document.getElementById("txtPort").value;
      // let baudRate = parseInt(document.getElementById("txtBaudRate").value);
      // let dataBits = parseInt(document.getElementById("txtDataBits").value);
      // let stopBits = parseInt(document.getElementById("txtStopBits").value);
      // let parity = parseInt(document.getElementById("txtParity").value);
      // let content = document.querySelector("#content");

      // 获取元素
      let smoke = document.querySelector("#smoke");
      let temperature = document.querySelector("#temperature");
      let isBody = document.querySelector("#isBody");
      let isAlarm = document.querySelector("#isAlarm");
      let isFan = document.querySelector("#isFan");
      let isProtection = document.querySelector("#isProtection");
      // let isManual = document.querySelector("#isManual");

      document.querySelector("#open").addEventListener("click", async () => {
        // 提示用户选择串口
        const port = await navigator.serial.requestPort();
        // 获取用户之前授予该网站访问权限的所有串口。
        // const ports = await navigator.serial.getPorts();
        // console.log(ports);
        await port.open({
          baudRate: 9600, //波特率
          dataBits: 8, //数据位
          parity: "none", //奇偶校验
          stopBits: 1, //停止位
          flowControl: "none",
        });

        while (port.readable) {
          const textDecoder = new TextDecoderStream();
          const readableStreamClosed = port.readable.pipeTo(textDecoder.writable);
          const reader = textDecoder.readable.getReader();

          try {
            // 监听来自串行设备的数据。
            let str = "";
            let arr = [];
            while (true) {
              const { value, done } = await reader.read();
              if (done) {
                // 允许稍后关闭串口。
                reader.releaseLock();
                break;
              }
              // value 是一个 string
              // console.log(value);
              str += value;
              arr = str.split("\n");
              if (arr.length > 1) {
                str = arr[0];
                console.log(str);
                str = str.slice(1, 17);
                let data = str.split(",");
                smoke.innerHTML = data[0];
                temperature.innerHTML = data[1] + "℃";
                isBody.innerHTML = data[2] == 1 ? "有人" : "无人";
                isAlarm.innerHTML = data[3] == 1 ? "报警" : "正常";
                isFan.innerHTML = data[4] == 1 ? "开启" : "关闭";
                isProtection.innerHTML =
                  data[5] == 2 ? "开启" : data[5] == 1 ? "布防中" : "未布防";
                // isManual.innerHTML = data[6] ? "是" : "否";
                str = "";
              }
            }
          } catch (error) {
            alert("系统出错，请联系管理员");
          }
        }
      });
    })();
  }
});
